package com.server;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.database.CustomerDB;

public class CustomerRegisterServlet extends CustomerServlet
{
	private static final long serialVersionUID = 2L;
	private final String className = "Customer Register Servlet: ";
	
	

	@Override
	//@requires HttpServletRequest !=NULL,  HttpServletResponse !=NULL ;
    //@assignable username,password,firstname,lastname,email,phone,loyaltypoint,msg;
    //@ensures CustomerDB db = new CustomerDB;
	//@signals_only RuntimeException, IOException,ServletException;
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException
	{
		ConnectDB();
		CustomerDB temp = new CustomerDB();
		temp.Setup(connection);
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String firstname = req.getParameter("firstname");
		String lastname = req.getParameter("lastname");
		String email = req.getParameter("email");
		String phone = "123";//req.getParameter("phone");
		int loyaltypoint = 1000;
		String msg = "";
				
		try //check the phone number, username and psw. Registration success if all the info is entered correctly
		{
			if (phone.length() > 10)
			{
				msg = "invalid phone number";
			}
			else if (temp.UserExists(username))
			{
				msg = "Username exists. Please pick another one!";
			}
			else if (username.isEmpty() || password.isEmpty() || phone.isEmpty())
			{
				msg = "Missing fields. Username, password, and phone number are required.";
			}
			// you need to put a else if (phone.isNotANumber) here
			else if( NaN(phone))
			{
				msg = "invalid phone number";
			}
			else if( Integer.parseInt(phone)<0)
			{
				msg = "negative number is not allowed";
			}
			else
			{
				//@edward this is the bug. check that string phone is indeed a number. if it is, insert 
				// into the database.
				int phoneNum = Integer.parseInt(phone);
				CustomerDB db = new CustomerDB(username, password, firstname, lastname, email, phoneNum, loyaltypoint);
				db.Setup(connection);
				db.Insert();
				msg = "Hi, " + firstname + "! Registration success!";
			}
			
			req.setAttribute("msg", msg);
			
			req.getRequestDispatcher("customer/register_result_customer.jsp").forward(req, resp);
		} 
		catch (SQLException e) 
		{
			e.printStackTrace();
		}
	}
	

}

